<?php
/**
 * 我的考勤
 * @author coldarmy
 * **/
apf_require_controller('Oa_Attendance_Abstract');
apf_require_class('Bll_Attendance_LeaveRecord');
apf_require_class('Bll_Attendance_ApplyType');
class Oa_Attendance_MyApplyController extends Oa_Attendance_AbstractController {
    /** 上下分页 **/
    const PAGEROW = 12;

    public function handle_request() {
        $params = $this->request->get_parameters();

        if(isset($params['do']) && $params['do'] == 'cancel' && $params['id'] > 0) {
            $this->cancel_apply($params['id']);
        }
        $keep = $params;

        $list = $this->get_apply_list($params);
        $this->request->set_attribute('list',$list);
        $this->request->set_attribute('count',count($list)-1);
        $t_bll = new Bll_Attendance_ApplyType();
        $type = $t_bll->get_all_leave_type();
        $this->request->set_attribute('type',$type);
        if(date('H') > 0 && date('H') < 12) {
            $ma = '上午';
        } else {
            $ma = '下午';
        }
        $this->page['curr_time'] = date('Y').'年'.date('m').'月'.date('d')."日&nbsp;&nbsp;&nbsp;星期".Tools_Tools::get_instance()->convert_chinese_week(date('w'))."&nbsp;&nbsp;&nbsp;&nbsp;".$ma."&nbsp;&nbsp;&nbsp;".date('h:i');
        $this->request->set_attribute('page',$this->page);
        $this->request->set_attribute('keep',$keep);

        return 'Oa_Attendance_MyApply';
    }

    /**
     * 取消申请
     *
     * @param mixed $id
     * @access private
     * @return void
     */
    private function cancel_apply($id) {
        if(empty($id)) {
            return '';
        }
        $bll = new Bll_Attendance_LeaveRecord();
        $record = $bll->get_leave_by_id($id);
        if(empty($record)) {
            return '';
        }
        $leave_time = $record['leave_time'];
        $leave_time = 0 - $leave_time;
        $data['status'] = '已撤销';
        $data['is_cancel'] = 1;

        //对audit_list 表做逻辑删除,对于未审批，已撤销的情况
        //1. 对于请假小于等于三天，出差 的类型，撤销前还没审批的，删除audit_list记录，状态改为3
        if($record['status'] == '未审核'){
            apf_require_class('Bll_Attendance_LeaveRecordLog');
            $record_log_bll = new  Bll_Attendance_LeaveRecordLog;
            $record_logs = $record_log_bll->get_log_by_ids($id);
            $count_record_logs = count($record_logs);

            //取audit_list 记录
            apf_require_class('Bll_Attendance_Audit');
            $audit_bll =  new Bll_Attendance_Audit;
            $audit_lists = $audit_bll->get_audit_by_leave_id($id);
            $count_audit = count($audit_lists);

            if($record['type'] == '出差' or $record['leave_time'] <= 3){
                if($count_audit){//已经在未审批里面了
                    $audit_bll->update_audit_list(array('status'=>3), array('leave_id'=>$id));
                }
            }
            //2. 大于三天的假期
            else{
                if($count_audit ==1){
                    //判断一级领导是否有批准，未批准做更新操作，已批不做操作
                    if($audit_lists[0]['status'] ==1){
                        $audit_bll->update_audit_list(array('status'=>3), array('leave_id'=>$id,'uid'=>$record['r_user_id']));
                    }
                }
                elseif ($count_audit ==2 and $audit_lists[1]['status'] ==1){//只有二级领导没有审批，更新其状态
                    $audit_bll->update_audit_list(array('status'=>3), array('leave_id'=>$id,'uid'=>$record['b_user_id']));
                }
            }
        }

        $back = $bll->update($id,$this->uinfo['user_id'],$data);
        $daily_bll = new Bll_Attendance_DailyReport();
        $daily_bll->make_leave_data($id,4);
        //如果撤销成功，请假类型为年假时，返回年假天数
        if($back && $record['type'] == '年假') {
             apf_require_class('Bll_Attendance_UserExt');
             $uext = new Bll_Attendance_UserExt();
             $back = $uext->update_used_annual($this->uinfo['user_id'], $leave_time);
        }
        if($back) {
            $this->response->redirect('/myapply/',false,false);
        }
    }

    /**
     * 根据时间点获取7天的数据
     * access_date >= $start AND access_date <= $end
     * @param mixed $params
     * @access private
     * @return void
     */
    private function get_apply_list($params) {
        $result = array();
        //$this->uinfo['user_id'] = 3000;
        //如果用户未登录，返回空数组
        if(empty($this->uinfo['user_id'])) {
            return $result;
        }
        apf_require_class('Tools_Tools');
        $where['user_id'] = $this->uinfo['user_id'];
        if($params['type']) {
            $where['type'] = $params['type'];
        }
        if($params['status']) {
            $where['status'] = $params['status'];
        }
        $page = 1;
        if($params['p'] && $params['p'] > 1) {
            $page = $params['p'];
        }
        $bll = new Bll_Attendance_LeaveRecord();
        $count = $bll->get_count_by_condition($where);
        if($count <= 0) {
            return $result;
        }
        $result = $bll->get_leave_record_data($where,self::PAGEROW,$page);
        $result = $this->rebuild_data($result);
        if($count > self::PAGEROW) {
            $url_params = $where;
            unset($url_params['user_id']);
            $multipage = $this->build_multiPage_info($count,$page,$url_params);
            $this->request->set_attribute('multipage',$multipage);
        }

        return $result;
    }

    /**
     * 重组列表数据
     *
     * @param mixed $data
     * @access private
     * @return void
     */
    private function rebuild_data($data){
        $result = array();
        if(empty($data)) {
            return $result;
        }
        $leaveids = array();
        foreach ($data as $key => $val) {
           $leaveids[] = $val['id'];
           if($val['r_user_id']) {
               $userids[] = $val['r_user_id'];
               if($val['b_user_id'] && $val['b_user_id']!=6932) {//如果是二级审批人是mike的，不显示mike
                    $userids[] = $val['b_user_id'];
               }
           }
        }
        apf_require_class('Bll_Attendance_LeaveRecordLog');
        $l_bll = new Bll_Attendance_LeaveRecordLog();
        $leave = $l_bll->get_log_by_ids($leaveids);
        //重新组装数据
        if($leave) {
            foreach ($leave as $k => $v) {
                $deallog[$v['leave_id']][$v['operator']] = $v['action'];
            }
        }
        apf_require_class('Bll_Attendance_UserInfo');
        $u_bll = new Bll_Attendance_UserInfo();
        $userids=array_unique($userids);//去重
        $user  = $u_bll->get_user_by_ids($userids);

        if($user) {
            foreach ($user as $k => $v) {
                $alluser[$v['user_id']] = $v;
            }
        }
        foreach ($data as $key => $val) {
            $val['can_cancel'] = 0;
            $val['need'] = 0;
            $contact_time="";
            if($val['start_time']){
                $contact_time .= $this->format_date($val['start_time']);
            }
            if($val['start_time'] && $val['end_time']){
                $contact_time .=' - ';
            }
            if($val['end_time']){
                $contact_time .= $this->format_date($val['end_time']);
            }
            $val['contact_time'] = $contact_time;
            $val['apply_time'] = $this->format_date_two($val['apply_time']);
            //需要上传证明
            if($val['type'] == '病假' || $val['type'] == '陪产假' || $val['type'] == '产检' || $val['type'] == '产前假' || $val['type'] == '婚假') {
               if(empty($val['img']) && ((time() - $val['apply_time_ext']) < 604800)) {
                   $val['need'] = 1;
               }
             }
            //如果未到结束 可以撤销
            if(date('Ymd',strtotime($val['end_time'])) >= date('Ymd') && $val['status'] != '已撤销') {
                $val['can_cancel'] = 1;
            }
            //未审核允许撤销
            if($val['status'] == '未审核') {
                $val['can_cancel'] = 1;
            }
            if($val['status'] == '已驳回') {
                $val['can_cancel'] = 0;
            }
            //批准人
            $val['passinfo'] = "";
            if($val['r_user_id'] && $val['is_cancel'] != 1) {
                $status = '';
               if($val['status']) {
                    $status = $val['status'];
               }
               $log = $deallog[$val['id']][$val['r_user_id']];
               if($log && $log > 1){
                    $status = $log == 2?'已批准':'已驳回';
               }
               $val['passinfo'] .= $user[$val['r_user_id']]['name']."($status)";
            }
            if($val['b_user_id'] && $val['is_cancel'] != 1 && $val['b_user_id']!=6932) {
               if($val['status']) {
                    $status = $val['status'];
               }
               $log = $deallog[$val['id']][$val['b_user_id']];
               if($log && $log > 1){
                    $status = $log == 2?'已批准':'已驳回';
               }
               $val['passinfo'] .= ", ".$user[$val['b_user_id']]['name']."($status)";
           }
           //出差审批人
           if($val['type'] == "出差"){
                 apf_require_class("Bll_Attendance_Trip");
                 $trip_bll = new Bll_Attendance_Trip;
                 $user_info = $trip_bll->get_dpt_info();
                 //部门id

                 //$val['passinfo'] = "{$user_info['name']}($status)";
           }
           //已撤销显示
           if( $val['status'] == '已撤销'){
                 $val['passinfo'] = "(已撤销)";
           }
           $result[] = $val;
        }
        return $result;
    }

    /**
     * 格式化时间
     *
     * @param mixed $date
     * @access private
     * @return void
     */
    private function format_date($date) {
        $result = 0;
        if(empty($date)) {
            return $result;
        }
        $lenght = strlen($date);
        $result = substr($date,0,4).'年'.intval(substr($date,5,2)).'月'.intval(substr($date,8,2)).'日';
        if($lenght > 13) {
            $result .= intval(substr($date, -5,2)).'点';
        }
        return $result;
    }

    /**
     * 提交时间
     *
     * @param mixed $date
     * @access private
     * @return void
     */
    private function format_date_two($date) {
        $result = 0;
        if(empty($date)) {
            return $result;
        }
        return $date;
        $lenght = strlen($date);
        $result = substr($date,0,4).'年'.intval(substr($date,5,2)).'月'.intval(substr($date,8,2)).'日';
        if($lenght > 13) {
            $result .= intval(substr($date, -8,2)).'点';
        }
        return $result;
    }

    /**
     * 获取翻页
     * @param unknown_type $totalnum 总的页数
     * @param unknown_type $page_num 当前第几页
     * @param array $url_params
     * @param int $uid 用户ID
     */
    public function build_multiPage_info($totalnum,$page_num = 0,$url_params = array()) {
        apf_require_class('Tools_MultiPage');
        //翻页信息
        $url = "/myapply/";
        $total_rows = $totalnum;
        if($page_num <= 0){$page_num = 1;}
        $url_params['p'] = $page_num;

        $multipage = Tools_MultiPage::multiPage($url,$url_params, '', $total_rows, self::PAGEROW, 10);
        return $multipage;
    }

}
